package com.cnaaa.pay.service.impl;

import com.cnaaa.pay.dao.StringIdDao;
import com.cnaaa.pay.service.StringIdService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 2018/10/9 Create by 郭文梁
 * AbstractIntegerIdServiceImpl
 * 基础服务实现类
 *
 * @author 郭文梁
 * @date 2018/10/9
 */
public abstract class AbstractStringIdServiceImpl<T> implements StringIdService<T> {
    @Override
    public T save(T o) {
        return getRepository().save(o);
    }

    @Override
    public List<T> list() {
        return getRepository().findAll();
    }

    @Override
    public List<T> list(int page, int size) {
        StringIdDao<T> repository = getRepository();
        Page<T> paged = repository.findAll(PageRequest.of(page - 1, size));
        return paged.stream().collect(Collectors.toList());
    }

    @Override
    public long getCount() {
        return getRepository().count();
    }

    @Override
    public T findById(String id) {
        Optional<T> rst = getRepository().findById(id);
        return rst.orElse(null);
    }

    @Override
    public int delete(String id) {
        getRepository().deleteById(id);
        return 1;
    }

    @Override
    public T update(T o) {
        return getRepository().save(o);
    }

    /**
     * 获取持久化对象，由子类实现
     *
     * @return 持久化对象
     */
    public abstract StringIdDao<T> getRepository();
}
